﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;

namespace Zatify.API.Controllers
{
    public class BusinessController : BaseController
    {
        public string GetProfile(string token)
        {
            try
            {
                DataTable dt = DataAccess.GetDataTable("spAPI_Business_GetProfile",
                    new string[] { "Token" }, new object[] { token });

                if (Convert.ToInt32(dt.Rows[0]["IdResult"]) == 0)
                    return CommonLib.ErrorXml("Invalid token", "1").ToString();
                else
                    return CommonLib.OkXml(new string[] { "Data" }, new string[] { dt.Rows[0]["Result"].ToString() }).ToString();
            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "100").ToString();
            }

        }

        public string Nearby(string token, decimal lat, decimal @long)
        {
            try
            {
                DataTable dt = DataAccess.GetDataTable("spAPI_Business_Nearby",
                    new string[] { "Token", "Lat", "Long" }, new object[] { token, lat, @long });

                if (Convert.ToInt32(dt.Rows[0]["IdResult"]) == 0)
                    return CommonLib.ErrorXml("Invalid token", "1").ToString();
                else
                    return CommonLib.OkXml(new string[] { "Data" }, new string[] { dt.Rows[0]["Result"].ToString() }).ToString();
            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "100").ToString();
            }
        }

        public string GetDeals(string token, decimal latitude, decimal longtitude)
        {
            try
            {
                DataTable dt = DataAccess.GetDataTable("spAPI_Business_GetDeals",
                    new string[] { "Token", "Latitude", "Longtitude" }, new object[] { token, latitude, longtitude });

                if (Convert.ToInt32(dt.Rows[0]["IdResult"]) == 0)
                    return CommonLib.ErrorXml("Invalid token", "1").ToString();
                else
                    return CommonLib.OkXml(new string[] { "Data" }, new string[] { dt.Rows[0]["Result"].ToString() }).ToString();
            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "100").ToString();
            }
        }

        public string GetDealsByBusiness(string token, int businessId, decimal latitude, decimal longitude)
        {
            try
            {
                DataTable dt = DataAccess.GetDataTable("spAPI_User_GetAllActivePromotionsByBusiness",
                    new string[] { "Token", "businessId", "latitude", "longitude" }, new object[] { token, businessId, latitude, longitude });

                if (Convert.ToInt32(dt.Rows[0]["IdResult"]) == 0)
                    return CommonLib.ErrorXml("Invalid token", "1").ToString();
                else
                    return CommonLib.OkXml(new string[] { "Data" }, new string[] { dt.Rows[0]["Result"].ToString() }).ToString();
            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "100").ToString();
            }
        }

        public string GetCoo(string streetAddress, string streetAddress2, string city, string state, string zip)
        {
            decimal lt = 0;
            decimal lg = 0;
            //string searchAddress = ("1600") + " " + ("Amphitheatre Parkway, Mountain View") + " " + ("CA");
            string searchAddress = (zip ?? "") + " " + (streetAddress ?? "") + " " + (streetAddress2 ?? "") + " " + (state ?? "");
            if (CommonLib.GetLatLong(searchAddress, ref lt, ref lg))
            {
                string coo = "";
                coo += lt.ToString("#0.00000000");
                coo += ";" + lg.ToString("#0.00000000");

                return coo;
            }
            else return "";
        }

        /*public string TestGmt()
        {
            string result = "";

            decimal lt = 0;
            decimal lg = 0;
            string searchAddress = ("1600") + " " + ("Amphitheatre Parkway, Mountain View") + " " + ("CA");
            searchAddress = ("89121") + " " + ("2435 E. Tropicana Ave.") + " " + ("NV"); 

            if (CommonLib.GetLatLong(searchAddress, ref lt, ref lg))
            {
                int gmt = CommonLib.GetGmt(lt, lg);
                result = gmt.ToString();
            }
            
            return result;
        }*/

        public string Register(
            // step 1 of wizard
            string id
            , string email
            , string businessName
            , string web
            , string businessPhone
            , string cellPhone
            , string tollFreePhone
            , string fax
            , string streetAddress
            , string streetAddress2
            , string city
            , string state
            , string zip

            // step 2: business owner will enter business description and business hours
            , string description
            , string referencedBy
            , string sunFrom
            , string sunTo
            , bool sunClosed
            , string monFrom
            , string monTo
            , bool monClosed
            , string tueFrom
            , string tueTo
            , bool tueClosed
            , string wedFrom
            , string wedTo
            , bool wedClosed
            , string thuFrom
            , string thuTo
            , bool thuClosed
            , string friFrom
            , string friTo
            , bool friClosed
            , string satFrom
            , string satTo
            , bool satClosed

            // step 3: the user will pick relevant business categories
            , string categories
            , string newCategory1
            , string newCategory2
            , string newCategory3

            // step 4: the business owner will Register his business location
            , decimal? latitude
            , decimal? longitude

            // step 5: The business owner will have to provide credit or debit card information
            , string cardId
            , bool useBusinessAddress
            , string billingStreetAddress
            , string billingStreetAddress2
            , string billingCity
            , string billingState
            , string billingZip)
        {
            string[] userpass = null;
            bool latlongError = false;
            int gmt = 0;
            string errMessage = "";

            try
            {
                if ((latitude == null) || (longitude == null))
                {
                    decimal lt = 0;
                    decimal lg = 0;
                    string searchAddress = (zip ?? "") + " " + (streetAddress ?? "") + " " + (streetAddress2 ?? "") + " " + (state ?? "");
                    if (CommonLib.GetLatLong(searchAddress, ref lt, ref lg))
                    {
                        if (latitude == null)
                            latitude = lt;
                        if (longitude == null)
                            longitude = lg;
                    }
                    else
                        latlongError = true;
                }

                if (!latlongError)
                {
                    gmt = CommonLib.GetGmt(Convert.ToDecimal(latitude), Convert.ToDecimal(longitude), out errMessage);
                    if (gmt == -100)
                    {
                        gmt = 0;
                        latlongError = true;
                    }
                }

                id = Encoding.UTF8.GetString(Convert.FromBase64String(id));
                userpass = id.Split(';');

                cardId = Encoding.UTF8.GetString(Convert.FromBase64String(cardId));
                string[] cardInfo = cardId.Split(';');

                DataTable dt = DataAccess.GetDataTable("spAPI_Business_Register",
                    new string[]
                    { 
                        "login"
                        ,"password"
                        ,"email"
                        ,"businessName"
                        ,"web"
                        ,"businessPhone"
                        ,"cellPhone"
                        ,"tollFreePhone"
                        ,"fax"
                        ,"streetAddress"
                        ,"streetAddress2"
                        ,"city"
                        ,"state"
                        ,"zip"
                        ,"description"
                        ,"referencedBy"
                        ,"sunFrom"
                        ,"sunTo"
                        ,"sunClosed"
                        ,"monFrom"
                        ,"monTo"
                        ,"monClosed"
                        ,"tueFrom"
                        ,"tueTo"
                        ,"tueClosed"
                        ,"wedFrom"
                        ,"wedTo"
                        ,"wedClosed"
                        ,"thuFrom"
                        ,"thuTo"
                        ,"thuClosed"
                        ,"friFrom"
                        ,"friTo"
                        ,"friClosed"
                        ,"satFrom"
                        ,"satTo"
                        ,"satClosed"
                        ,"categories"
                        ,"newCategory1"
                        ,"newCategory2"
                        ,"newCategory3"
                        ,"latitude"
                        ,"longitude"
                        ,"gmt"
	                    ,"creditCardNo"
	                    ,"creditCardExpDate"
	                    ,"creditCardName"
	                    ,"creditCardPin"
                        ,"useBusinessAddress"
                        ,"billingStreetAddress"
                        ,"billingStreetAddress2"
                        ,"billingCity"
                        ,"billingState"
                        ,"billingZip"
                        ,"PictureContentType"
                        ,"Picture"
                    },
                    new object[]
                    {
                        userpass[0]
                        ,userpass[1]
                        ,email ?? ""
                        ,businessName ?? ""
                        ,web ?? ""
                        ,businessPhone ?? ""
                        ,cellPhone ?? ""
                        ,tollFreePhone ?? ""
                        ,fax ?? ""
                        ,streetAddress ?? ""
                        ,streetAddress2 ?? ""
                        ,city ?? ""
                        ,state ?? ""
                        ,zip ?? ""
                        ,description ?? ""
                        ,referencedBy ?? ""
                        ,sunFrom ?? DateTime.Now.ToShortTimeString()
                        ,sunTo ??  DateTime.Now.ToShortTimeString()
                        ,sunClosed
                        ,monFrom ??  DateTime.Now.ToShortTimeString()
                        ,monTo ??  DateTime.Now.ToShortTimeString()
                        ,monClosed
                        ,tueFrom ?? DateTime.Now.ToShortTimeString()
                        ,tueTo ?? DateTime.Now.ToShortTimeString()
                        ,tueClosed
                        ,wedFrom ?? DateTime.Now.ToShortTimeString()
                        ,wedTo ?? DateTime.Now.ToShortTimeString()
                        ,wedClosed
                        ,thuFrom ?? DateTime.Now.ToShortTimeString()
                        ,thuTo ?? DateTime.Now.ToShortTimeString()
                        ,thuClosed
                        ,friFrom ?? DateTime.Now.ToShortTimeString()
                        ,friTo ?? DateTime.Now.ToShortTimeString()
                        ,friClosed
                        ,satFrom ?? DateTime.Now.ToShortTimeString()
                        ,satTo ?? DateTime.Now.ToShortTimeString()
                        ,satClosed
                        ,categories ?? ""
                        ,newCategory1 ?? ""
                        ,newCategory2 ?? ""
                        ,newCategory3 ?? ""
                        ,latitude
                        ,longitude
                        ,gmt
	                    ,cardInfo[0]
	                    ,cardInfo[2]
	                    ,cardInfo[1]
	                    ,cardInfo[3]
                        ,useBusinessAddress
                        ,billingStreetAddress ?? ""
                        ,billingStreetAddress2 ?? ""
                        ,billingCity ?? ""
                        ,billingState ?? ""
                        ,billingZip ?? ""
                        ,Request.ContentLength > 0 ? Request.ContentType : ""
                        ,Request.ContentLength > 0 ? Request.BinaryRead(Request.ContentLength) : null
                    });

                if (latlongError)
                    return CommonLib.ErrorXml("Could not get coordinates or time offset of business", "101", new string[] { "Data" }, new string[] { dt.Rows[0]["SecurityToken"].ToString() }).ToString();
                else
                {
                    switch (Convert.ToInt32(dt.Rows[0]["IdResult"]))
                    {
                        case 0:
                            return CommonLib.ErrorXml("Referrer is not found", "3").ToString();
                        case -1:
                            return CommonLib.ErrorXml("Phone already exists", "4").ToString();
                        case -2:
                            return CommonLib.ErrorXml("Email already exists", "5").ToString();
                        case -3:
                            return CommonLib.ErrorXml("Invalid zip code", "6").ToString();
                        case -4:
                            return CommonLib.ErrorXml("Invalid billing zip code", "7").ToString();
                        default:
                            return CommonLib.OkXml(new string[] { "Data" }, new string[] { dt.Rows[0]["SecurityToken"].ToString() }).ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("PK_UserBusinessLogins"))
                {
                    return CommonLib.ErrorXml(string.Format("Login '{0}' already exists", userpass[0]), "1").ToString();
                }
                else
                {
                    return CommonLib.ErrorXml(ex.Message, "2").ToString();
                }
            }
        }

        public string RegisterStep1(
            string id
            , string email
            , string businessName
            , string web
            , string businessPhone
            , string cellPhone
            , string tollFreePhone
            , string fax
            , string streetAddress
            , string streetAddress2
            , string city
            , string state
            , string zip)
        {
            string[] userpass = null;
            bool latlongError = false;

            decimal? latitude = null;
            decimal? longitude = null;
            int gmt = 0;
            string errMessage = "";

            try
            {
                if ((latitude == null) || (longitude == null))
                {
                    decimal lt = 0;
                    decimal lg = 0;
                    string searchAddress = (zip ?? "") + " " + (streetAddress ?? "") + " " + (streetAddress2 ?? "") + " " + (state ?? "");
                    if (CommonLib.GetLatLong(searchAddress, ref lt, ref lg))
                    {
                        if (latitude == null)
                            latitude = lt;
                        if (longitude == null)
                            longitude = lg;
                    }
                    else
                        latlongError = true;
                }

                if (!latlongError)
                {
                    gmt = CommonLib.GetGmt(Convert.ToDecimal(latitude), Convert.ToDecimal(longitude), out errMessage);
                    if (gmt == -100)
                    {
                        gmt = 0;
                        latlongError = true;
                    }
                }

                id = Encoding.UTF8.GetString(Convert.FromBase64String(id));
                userpass = id.Split(';');

                DataTable dt = DataAccess.GetDataTable("spAPI_Business_RegisterStep1",
                    new string[]
                    { 
                        "login"
                        ,"password"
                        ,"email"
                        ,"businessName"
                        ,"web"
                        ,"businessPhone"
                        ,"cellPhone"
                        ,"tollFreePhone"
                        ,"fax"
                        ,"streetAddress"
                        ,"streetAddress2"
                        ,"city"
                        ,"state"
                        ,"zip"
                        ,"latitude"
                        ,"longitude"
                        ,"gmt"
                    },
                    new object[]
                    {
                        userpass[0]
                        ,userpass[1]
                        ,email ?? ""
                        ,businessName ?? ""
                        ,web ?? ""
                        ,businessPhone ?? ""
                        ,cellPhone ?? ""
                        ,tollFreePhone ?? ""
                        ,fax ?? ""
                        ,streetAddress ?? ""
                        ,streetAddress2 ?? ""
                        ,city ?? ""
                        ,state ?? ""
                        ,zip ?? ""
                        ,latitude
                        ,longitude
                        ,gmt
                    });
                
                    switch (Convert.ToInt32(dt.Rows[0]["IdResult"]))
                    {
                        case 0:
                            return CommonLib.ErrorXml("Referrer is not found", "3").ToString();
                        case -1:
                            return CommonLib.ErrorXml("Phone already exists", "4").ToString();
                        case -2:
                            return CommonLib.ErrorXml("Email already exists", "5").ToString();
                        case -3:
                            return CommonLib.ErrorXml("Invalid zip code", "6").ToString();
                        case -4:
                            return CommonLib.ErrorXml("Invalid billing zip code", "7").ToString();
                        default:
                            if (latlongError)
                            {
                                return CommonLib.ErrorXml("Could not get coordinates or time offset of business", "101", new string[] { "Data" }, new string[] { dt.Rows[0]["SecurityToken"].ToString() }).ToString();
                            }
                            else
                            {
                            return CommonLib.OkXml(new string[] { "Data" }, new string[] { dt.Rows[0]["SecurityToken"].ToString() }).ToString();                            }
                    }
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("PK_UserBusinessLogins"))
                {
                    return CommonLib.ErrorXml(string.Format("Login '{0}' already exists", userpass[0]), "1").ToString();
                }
                else
                {
                    return CommonLib.ErrorXml(ex.Message, "2").ToString();
                }
            }
        }

        public string RegisterStep1Update(
            string token
            , string id
            , string email
            , string businessName
            , string web
            , string businessPhone
            , string cellPhone
            , string tollFreePhone
            , string fax
            , string streetAddress
            , string streetAddress2
            , string city
            , string state
            , string zip)
        {
            string[] userpass = null;
            bool latlongError = false;

            decimal? latitude = null;
            decimal? longitude = null;
            int gmt = 0;
            string errMessage = "";

            try
            {
                if ((latitude == null) || (longitude == null))
                {
                    decimal lt = 0;
                    decimal lg = 0;
                    string searchAddress = (zip ?? "") + " " + (streetAddress ?? "") + " " + (streetAddress2 ?? "") + " " + (state ?? "");
                    if (CommonLib.GetLatLong(searchAddress, ref lt, ref lg))
                    {
                        if (latitude == null)
                            latitude = lt;
                        if (longitude == null)
                            longitude = lg;
                    }
                    else
                        latlongError = true;
                }

                if (!latlongError)
                {
                    gmt = CommonLib.GetGmt(Convert.ToDecimal(latitude), Convert.ToDecimal(longitude), out errMessage);
                    if (gmt == -100)
                    {
                        gmt = 0;
                        latlongError = true;
                    }
                }

                id = Encoding.UTF8.GetString(Convert.FromBase64String(id));
                userpass = id.Split(';');

                DataTable dt = DataAccess.GetDataTable("spAPI_Business_RegisterStep1Update",
                    new string[]
                    { 
                        "token"
                        ,"password"
                        ,"email"
                        ,"businessName"
                        ,"web"
                        ,"businessPhone"
                        ,"cellPhone"
                        ,"tollFreePhone"
                        ,"fax"
                        ,"streetAddress"
                        ,"streetAddress2"
                        ,"city"
                        ,"state"
                        ,"zip"
                        ,"latitude"
                        ,"longitude"
                        ,"gmt"
                    },
                    new object[]
                    {
                        token
                        ,userpass[1]
                        ,email ?? ""
                        ,businessName ?? ""
                        ,web ?? ""
                        ,businessPhone ?? ""
                        ,cellPhone ?? ""
                        ,tollFreePhone ?? ""
                        ,fax ?? ""
                        ,streetAddress ?? ""
                        ,streetAddress2 ?? ""
                        ,city ?? ""
                        ,state ?? ""
                        ,zip ?? ""
                        ,latitude
                        ,longitude
                        ,gmt
                    });

                if (latlongError)
                    return CommonLib.ErrorXml("Could not get coordinates or time offset of business", "101", new string[] { "Data" }, new string[] { dt.Rows[0]["SecurityToken"].ToString() }).ToString();
                else
                {
                    switch (Convert.ToInt32(dt.Rows[0]["IdResult"]))
                    {
                        case 0:
                            return CommonLib.ErrorXml("Referrer is not found", "3").ToString();
                        case -1:
                            return CommonLib.ErrorXml("Phone already exists", "4").ToString();
                        case -2:
                            return CommonLib.ErrorXml("Email already exists", "5").ToString();
                        case -3:
                            return CommonLib.ErrorXml("Invalid zip code", "6").ToString();
                        case -4:
                            return CommonLib.ErrorXml("Invalid billing zip code", "7").ToString();
                        default:
                            return CommonLib.OkXml().ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "2").ToString();
            }
        }

        public string RegisterStep2(
            string token

            , string description
            , string referencedBy
            , string sunFrom
            , string sunTo
            , bool sunClosed
            , string monFrom
            , string monTo
            , bool monClosed
            , string tueFrom
            , string tueTo
            , bool tueClosed
            , string wedFrom
            , string wedTo
            , bool wedClosed
            , string thuFrom
            , string thuTo
            , bool thuClosed
            , string friFrom
            , string friTo
            , bool friClosed
            , string satFrom
            , string satTo
            , bool satClosed

            , string categories
            , string newCategory1
            , string newCategory2
            , string newCategory3

            , string cardId
            , bool useBusinessAddress
            , string billingStreetAddress
            , string billingStreetAddress2
            , string billingCity
            , string billingState
            , string billingZip

            ,decimal? latitude
            ,decimal? longitude)
        {
            try
            {
                cardId = Encoding.UTF8.GetString(Convert.FromBase64String(cardId));
                string[] cardInfo = cardId.Split(';');

                int? gmt = null;
                if (latitude.HasValue && longitude.HasValue)
                {
                    string errMessage = "";
                    gmt = CommonLib.GetGmt(Convert.ToDecimal(latitude), Convert.ToDecimal(longitude), out errMessage);
                    if (gmt == -100)
                        gmt = null;
                }
                
                DataTable dt = DataAccess.GetDataTable("spAPI_Business_RegisterStep2",
                    new string[]
                    { 
                        "token"
                        ,"description"
                        ,"referencedBy"
                        ,"sunFrom"
                        ,"sunTo"
                        ,"sunClosed"
                        ,"monFrom"
                        ,"monTo"
                        ,"monClosed"
                        ,"tueFrom"
                        ,"tueTo"
                        ,"tueClosed"
                        ,"wedFrom"
                        ,"wedTo"
                        ,"wedClosed"
                        ,"thuFrom"
                        ,"thuTo"
                        ,"thuClosed"
                        ,"friFrom"
                        ,"friTo"
                        ,"friClosed"
                        ,"satFrom"
                        ,"satTo"
                        ,"satClosed"
                        ,"categories"
                        ,"newCategory1"
                        ,"newCategory2"
                        ,"newCategory3"
	                    ,"creditCardNo"
	                    ,"creditCardExpDate"
	                    ,"creditCardName"
	                    ,"creditCardPin"
                        ,"useBusinessAddress"
                        ,"billingStreetAddress"
                        ,"billingStreetAddress2"
                        ,"billingCity"
                        ,"billingState"
                        ,"billingZip"
                        ,"PictureContentType"
                        ,"Picture"
                        ,"latitude"
                        ,"longitude"
                        ,"gmt"
                    },
                    new object[]
                    {
                        token
                        ,description ?? ""
                        ,referencedBy ?? ""
                        ,sunFrom ?? DateTime.UtcNow.ToShortTimeString()
                        ,sunTo ??  DateTime.UtcNow.ToShortTimeString()
                        ,sunClosed
                        ,monFrom ??  DateTime.UtcNow.ToShortTimeString()
                        ,monTo ??  DateTime.UtcNow.ToShortTimeString()
                        ,monClosed
                        ,tueFrom ?? DateTime.UtcNow.ToShortTimeString()
                        ,tueTo ?? DateTime.UtcNow.ToShortTimeString()
                        ,tueClosed
                        ,wedFrom ?? DateTime.UtcNow.ToShortTimeString()
                        ,wedTo ?? DateTime.UtcNow.ToShortTimeString()
                        ,wedClosed
                        ,thuFrom ?? DateTime.UtcNow.ToShortTimeString()
                        ,thuTo ?? DateTime.UtcNow.ToShortTimeString()
                        ,thuClosed
                        ,friFrom ?? DateTime.UtcNow.ToShortTimeString()
                        ,friTo ?? DateTime.UtcNow.ToShortTimeString()
                        ,friClosed
                        ,satFrom ?? DateTime.UtcNow.ToShortTimeString()
                        ,satTo ?? DateTime.UtcNow.ToShortTimeString()
                        ,satClosed
                        ,categories ?? ""
                        ,newCategory1 ?? ""
                        ,newCategory2 ?? ""
                        ,newCategory3 ?? ""
	                    ,cardInfo[0]
	                    ,cardInfo[2]
	                    ,cardInfo[1]
	                    ,cardInfo[3]
                        ,useBusinessAddress
                        ,billingStreetAddress ?? ""
                        ,billingStreetAddress2 ?? ""
                        ,billingCity ?? ""
                        ,billingState ?? ""
                        ,billingZip ?? ""
                        ,Request.ContentLength > 0 ? Request.ContentType : ""
                        ,Request.ContentLength > 0 ? Request.BinaryRead(Request.ContentLength) : null
                        ,latitude
                        ,longitude
                        ,gmt
                    });

                switch (Convert.ToInt32(dt.Rows[0]["IdResult"]))
                {
                    case 0:
                        return CommonLib.ErrorXml("Referrer is not found", "3").ToString();
                    case -1:
                        return CommonLib.ErrorXml("Phone already exists", "4").ToString();
                    case -2:
                        return CommonLib.ErrorXml("Email already exists", "5").ToString();
                    case -3:
                        return CommonLib.ErrorXml("Invalid zip code", "6").ToString();
                    case -4:
                        return CommonLib.ErrorXml("Invalid billing zip code", "7").ToString();
                    default:
                        return CommonLib.OkXml().ToString();
                }
            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "2").ToString();
            }
        }

        public string Update(
            string token
            // step 1 of wizard
            , string id
            , string email
            , string businessName
            , string web
            , string businessPhone
            , string cellPhone
            , string tollFreePhone
            , string fax
            , string streetAddress
            , string streetAddress2
            , string city
            , string state
            , string zip

            // step 2: business owner will enter business description and business hours
            , string description
            , string referencedBy
            , string sunFrom
            , string sunTo
            , bool sunClosed
            , string monFrom
            , string monTo
            , bool monClosed
            , string tueFrom
            , string tueTo
            , bool tueClosed
            , string wedFrom
            , string wedTo
            , bool wedClosed
            , string thuFrom
            , string thuTo
            , bool thuClosed
            , string friFrom
            , string friTo
            , bool friClosed
            , string satFrom
            , string satTo
            , bool satClosed

            // step 3: the user will pick relevant business categories
            , string categories
            , string newCategory1
            , string newCategory2
            , string newCategory3

            // step 4: the business owner will Register his business location
            , decimal? latitude
            , decimal? longitude

            // step 5: The business owner will have to provide credit or debit card information
            , string cardId
            , bool useBusinessAddress
            , string billingStreetAddress
            , string billingStreetAddress2
            , string billingCity
            , string billingState
            , string billingZip)
        {
            string[] userpass = null;
            bool latlongError = false;
            int gmt = 0;
            string errMessage = "";
            try
            {
                if ((latitude == null) || (longitude == null))
                {
                    decimal lt = 0;
                    decimal lg = 0;
                    string searchAddress = (zip ?? "") + " " + (streetAddress ?? "") + " " + (streetAddress2 ?? "") + " " + (state ?? "");
                    if (CommonLib.GetLatLong(searchAddress, ref lt, ref lg))
                    {
                        if (latitude == null)
                            latitude = lt;
                        if (longitude == null)
                            longitude = lg;
                    }
                    else
                        latlongError = true;
                }

                if (!latlongError)
                {
                    gmt = CommonLib.GetGmt(Convert.ToDecimal(latitude), Convert.ToDecimal(longitude), out errMessage);
                    if (gmt == -100)
                    {
                        gmt = 0;
                        latlongError = true;
                    }
                }

                id = Encoding.UTF8.GetString(Convert.FromBase64String(id));
                userpass = id.Split(';');

                string[] cardInfo = null;
                if (!string.IsNullOrEmpty(cardId))
                {
                    cardId = Encoding.UTF8.GetString(Convert.FromBase64String(cardId));
                    cardInfo = cardId.Split(';');
                }

                DataTable dt = DataAccess.GetDataTable("spAPI_Business_Update",
                    new string[]
                    { 
                        "token"
                        ,"password"
                        ,"email"
                        ,"businessName"
                        ,"web"
                        ,"businessPhone"
                        ,"cellPhone"
                        ,"tollFreePhone"
                        ,"fax"
                        ,"streetAddress"
                        ,"streetAddress2"
                        ,"city"
                        ,"state"
                        ,"zip"
                        ,"description"
                        ,"referencedBy"
                        ,"sunFrom"
                        ,"sunTo"
                        ,"sunClosed"
                        ,"monFrom"
                        ,"monTo"
                        ,"monClosed"
                        ,"tueFrom"
                        ,"tueTo"
                        ,"tueClosed"
                        ,"wedFrom"
                        ,"wedTo"
                        ,"wedClosed"
                        ,"thuFrom"
                        ,"thuTo"
                        ,"thuClosed"
                        ,"friFrom"
                        ,"friTo"
                        ,"friClosed"
                        ,"satFrom"
                        ,"satTo"
                        ,"satClosed"
                        ,"categories"
                        ,"newCategory1"
                        ,"newCategory2"
                        ,"newCategory3"
                        ,"latitude"
                        ,"longitude"
                        ,"gmt"
	                    ,"creditCardNo"
	                    ,"creditCardExpDate"
	                    ,"creditCardName"
	                    ,"creditCardPin"
                        ,"useBusinessAddress"
                        ,"billingStreetAddress"
                        ,"billingStreetAddress2"
                        ,"billingCity"
                        ,"billingState"
                        ,"billingZip"
                        ,"PictureContentType"
                        ,"Picture"
                    },
                    new object[]
                    {
                        token
                        ,userpass[1]
                        ,email ?? ""
                        ,businessName ?? ""
                        ,web ?? ""
                        ,businessPhone ?? ""
                        ,cellPhone ?? ""
                        ,tollFreePhone ?? ""
                        ,fax ?? ""
                        ,streetAddress ?? ""
                        ,streetAddress2 ?? ""
                        ,city ?? ""
                        ,state ?? ""
                        ,zip ?? ""
                        ,description ?? ""
                        ,referencedBy ?? ""
                        ,sunFrom ?? DateTime.Now.ToShortTimeString()
                        ,sunTo ??  DateTime.Now.ToShortTimeString()
                        ,sunClosed
                        ,monFrom ??  DateTime.Now.ToShortTimeString()
                        ,monTo ??  DateTime.Now.ToShortTimeString()
                        ,monClosed
                        ,tueFrom ?? DateTime.Now.ToShortTimeString()
                        ,tueTo ?? DateTime.Now.ToShortTimeString()
                        ,tueClosed
                        ,wedFrom ?? DateTime.Now.ToShortTimeString()
                        ,wedTo ?? DateTime.Now.ToShortTimeString()
                        ,wedClosed
                        ,thuFrom ?? DateTime.Now.ToShortTimeString()
                        ,thuTo ?? DateTime.Now.ToShortTimeString()
                        ,thuClosed
                        ,friFrom ?? DateTime.Now.ToShortTimeString()
                        ,friTo ?? DateTime.Now.ToShortTimeString()
                        ,friClosed
                        ,satFrom ?? DateTime.Now.ToShortTimeString()
                        ,satTo ?? DateTime.Now.ToShortTimeString()
                        ,satClosed
                        ,categories ?? ""
                        ,newCategory1 ?? ""
                        ,newCategory2 ?? ""
                        ,newCategory3 ?? ""
                        ,latitude
                        ,longitude
                        ,gmt
	                    ,cardInfo == null ? "" : cardInfo[0]
	                    ,cardInfo == null ? "" : cardInfo[2]
	                    ,cardInfo == null ? "" : cardInfo[1]
	                    ,cardInfo == null ? "" : cardInfo[3]
                        ,useBusinessAddress
                        ,billingStreetAddress ?? ""
                        ,billingStreetAddress2 ?? ""
                        ,billingCity ?? ""
                        ,billingState ?? ""
                        ,billingZip ?? ""
                        ,Request.ContentLength > 0 ? Request.ContentType : ""
                        ,Request.ContentLength > 0 ? Request.BinaryRead(Request.ContentLength) : null
                    });

                if (latlongError)
                    return CommonLib.ErrorXml("Could not get coordinates or time offset of business", "101", new string[] { "Data" }, new string[] { token }).ToString();
                else
                {
                    switch (Convert.ToInt32(dt.Rows[0]["IdResult"]))
                    {
                        case 0:
                            return CommonLib.ErrorXml("Invalid token", "1").ToString();
                        case -3:
                            return CommonLib.ErrorXml("Invalid zip code", "6").ToString();
                        case -4:
                            return CommonLib.ErrorXml("Invalid billing zip code", "7").ToString();
                        case -2:
                            return CommonLib.ErrorXml("Email already exists (in users or in buisnesses)", "9").ToString();
                        case 1:
                            return CommonLib.OkXml().ToString();
                        default:
                            return CommonLib.ErrorXml("Unknown error", "2").ToString();
                    }
                }

            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "2").ToString();
            }
        }

        public ActionResult GetProfilePicture(string token)
        {
            try
            {
                DataTable dt = DataAccess.GetDataTable("spAPI_Business_GetProfilePicture",
                    new string[] { "Token" }, new object[] { token });
                return this.Image((byte[])dt.Rows[0]["Picture"], dt.Rows[0]["PictureContentType"].ToString());
            }
            catch { return null; }
        }

        public ActionResult GetProfilePictureById(string token, int businessId)
        {
            if (!CommonLib.UserCheckToken(token))
            {
                return null;
            }

            try
            {
                DataTable dt = DataAccess.GetDataTable("spAPI_Business_GetProfilePictureById",
                    new string[] { "Token", "businessId" }, new object[] { token, businessId });
                return this.Image((byte[])dt.Rows[0]["Picture"], dt.Rows[0]["PictureContentType"].ToString());
            }
            catch { return null; }
        }

        public string GetReviews(string token, int businessid)
        {
            try
            {
                DataTable dt = DataAccess.GetDataTable("spAPI_BusinessReview_GetList",
                    new string[] { "Token", "BusinessId" }, new object[] { token, businessid });

                if (Convert.ToInt32(dt.Rows[0]["IdResult"]) == 0)
                    return CommonLib.ErrorXml("Invalid token", "1").ToString();
                else
                    return CommonLib.OkXml(new string[] { "Data" }, new string[] { dt.Rows[0]["Result"].ToString() }).ToString();
            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "100").ToString();
            }
        }

        public string GetPromotions(string token)
        {
            try
            {
                DataTable dt = DataAccess.GetDataTable("spAPI_Business_GetPromotions",
                    new string[] { "Token" }, new object[] { token });

                if (Convert.ToInt32(dt.Rows[0]["IdResult"]) == 0)
                    return CommonLib.ErrorXml("Invalid token", "1").ToString();
                else
                    return CommonLib.OkXml(new string[] { "Data" }, new string[] { dt.Rows[0]["Result"].ToString() }).ToString();
            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "100").ToString();
            }
        }

        public string GetPromotionDetails(string token, int promotionId)
        {
            try
            {
                DataTable dt = DataAccess.GetDataTable("spAPI_Business_GetPromotionDetails",
                    new string[] { "Token", "PromotionId" }, new object[] { token, promotionId });

                switch (Convert.ToInt32(dt.Rows[0]["IdResult"]))
                {
                    case 1:
                        return CommonLib.OkXml(new string[] { "Data" }, new string[] { dt.Rows[0]["Result"].ToString() }).ToString();
                    case -1:
                        return CommonLib.ErrorXml("Promotion not found", "2").ToString();
                    default:
                        return CommonLib.ErrorXml("Invalid token", "1").ToString();
                }
            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "100").ToString();
            }
        }

        public string DeletePromotion(string token, int promotionId)
        {
            try
            {
                DataTable dt = DataAccess.GetDataTable("spAPI_Business_DeletePromotion",
                    new string[] { "Token", "PromotionId" }, new object[] { token, promotionId });

                if (Convert.ToInt32(dt.Rows[0]["IdResult"]) == 0)
                    return CommonLib.ErrorXml("Invalid token", "1").ToString();
                else
                    return CommonLib.OkXml().ToString();
            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "100").ToString();
            }
        }

        public string GetMessages(string token)
        {
            try
            {
                DataTable dt = DataAccess.GetDataTable("spAPI_UserBusiness_GetMessages",
                    new string[] { "Token", "TokenType" }, new object[] { token, "B" });

                if (Convert.ToInt32(dt.Rows[0]["IdResult"]) == 0)
                    return CommonLib.ErrorXml("Invalid token", "1").ToString();
                else
                    return CommonLib.OkXml(new string[] { "Data" }, new string[] { dt.Rows[0]["Result"].ToString() }).ToString();
            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "100").ToString();
            }

        }

        public string GetTransactionHistory(string token, int? promotionId, DateTime? dateOperation)
        {
            try
            {
                DataTable dt = DataAccess.GetDataTable("spAPI_Billing_Transaction_History",
                    new string[] { "Token", "PromotionId", "DateOperation" }, new object[] { token, promotionId, dateOperation });

                if (Convert.ToInt32(dt.Rows[0]["IdResult"]) == 0)
                    return CommonLib.ErrorXml("Invalid token", "1").ToString();
                else
                    return CommonLib.OkXml(new string[] { "Data" }, new string[] { dt.Rows[0]["Result"].ToString() }).ToString();
            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "100").ToString();
            }
        }

        public string GetCreditCardTransactionDetails(string token, int transactionId)
        {
            try
            {
                DataTable dt = DataAccess.GetDataTable("spAPI_Billing_Transaction_GetCreditCardTransaction",
                    new string[] { "Token", "transactionId" }, new object[] { token, transactionId });

                if (Convert.ToInt32(dt.Rows[0]["IdResult"]) == 0)
                    return CommonLib.ErrorXml("Invalid token", "1").ToString();
                else
                    return CommonLib.OkXml(new string[] { "Data" }, new string[] { dt.Rows[0]["Result"].ToString() }).ToString();
            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "100").ToString();
            }
        }

        public string GetPromotionTransactionDetails(string token, int promotionId, DateTime? date)
        {
            try
            {
                DataTable dt = DataAccess.GetDataTable("spAPI_Billing_Transaction_GetPromotionTransaction",
                    new string[] { "Token", "promotionId", "date" }, new object[] { token, promotionId, date });

                if (Convert.ToInt32(dt.Rows[0]["IdResult"]) == 0)
                    return CommonLib.ErrorXml("Invalid token", "1").ToString();
                else
                    return CommonLib.OkXml(new string[] { "Data" }, new string[] { dt.Rows[0]["Result"].ToString() }).ToString();
            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "100").ToString();
            }
        }

        public string AddPromotionBudget(string token, int promotionId, decimal amount, string name, string promotionText)
        {
            try
            {
                decimal summaFromRest;
                decimal summaForPay;

                // try for pay
                string result = CommonLib.PayPromotion(token, promotionId, amount, out summaForPay, out summaFromRest);
                if (!string.IsNullOrEmpty(result))
                    return result;
                
                List<string> paramName = new List<string>();
                List<object> paramValue = new List<object>();

                paramName.Add("Token");
                paramValue.Add(token);
                paramName.Add("PromotionId");
                paramValue.Add(promotionId);
                paramName.Add("SummaPay");
                paramValue.Add(summaForPay);
                paramName.Add("SummaRest");
                paramValue.Add(summaFromRest);
                paramName.Add("Name");
                paramValue.Add(name);
                paramName.Add("PromotionText");
                paramValue.Add(promotionText);

                if (Request.ContentLength > 0)
                {
                    paramName.Add("PictureContentType");
                    paramValue.Add(Request.ContentType);

                    paramName.Add("Picture");
                    paramValue.Add(Request.BinaryRead(Request.ContentLength));
                }

                DataTable dt = DataAccess.GetDataTable("spAPI_Promotion_BudgetAdd", paramName.ToArray(), paramValue.ToArray());

                switch (Convert.ToInt32(dt.Rows[0]["IdResult"]))
                {
                    case 1:
                        return CommonLib.OkXml().ToString();
                    case -1:
                        return CommonLib.ErrorXml("Promotion not found", "2").ToString();
                    default:
                        return CommonLib.ErrorXml("Invalid token", "1").ToString();
                }
            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "100").ToString();
            }
        }

        public string UpdateGmt()
        {
            DataTable dt = DataAccess.GetDataTable("spBusiness_GetList", null, null);

            int cntAll = dt.Rows.Count;
            int cntLatLong = 0;
            int cntUpd = 0;
            int cntErr = 0;
            string errMessage = "";

            StringBuilder sbErrors = new StringBuilder();

            foreach (DataRow dr in dt.Rows)
            {
                if (!dr.IsNull("Gmt"))
                    if (Convert.ToInt32(dr["Gmt"]) != 0)
                        continue;

                if ((!dr.IsNull("Latitude")) && (!dr.IsNull("Longitude")))
                {
                    ++cntLatLong;

                    decimal lt = Convert.ToDecimal(dr["Latitude"]);
                    decimal lg = Convert.ToDecimal(dr["Longitude"]);
                    int gmt = CommonLib.GetGmt(lt, lg, out errMessage);

                    CommonLib.Delay(1);

                    if (gmt != -100)
                    {
                        DataAccess.ExecuteSQL(string.Format("update business set gmt = {0} where businessid = {1}", gmt.ToString(), dr["BusinessId"].ToString()));
                        ++cntUpd;
                    }
                    else
                    {
                        sbErrors.AppendLine(string.Format("BusinessId: {0}, Lat: {1}, Long: {2}, ErrorGmt: {3}", dr["BusinessId"].ToString(), lt.ToString(), lg.ToString(), errMessage));
                        ++cntErr;
                    }

                }
            }

            return "All: " + cntAll.ToString() + ", with geo: " + cntLatLong.ToString() + ", updated gmt: " + cntUpd.ToString() + ", error gmt: " + cntErr.ToString() + Environment.NewLine + "Errors: " + Environment.NewLine + sbErrors.ToString();

        }
    }
}
